//文档地址： https://quanzhan.co/luch-request/
//luch-request
//Http 请求配置
import Request from 'luch-request'
import baseURL from '../config/baseURL'
import {
	httpWhiteList,
	jumpPage,
	tokenKey
} from './../config/whitelist.js'
// const BASE_API = 'https://yzs.hxreal.com/mixedState/'

const BASE_API = 'http://192.168.110.17:8002/mixedStateZY/'
// const BASE_API ='https://hgcc.metaxun.com/mixedState';
// const BASE_API = 'http://192.168.110.7:8002/mixedState/';
const http = new Request({
	baseURL: BASE_API, //设置请求的base url
	timeout: 300000, //超时时长5分钟,
	header: {
		'Content-Type': 'application/json'
	}
})
//请求拦截器
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	const token = uni.getStorageSync('token');
	const serverUrl = uni.getStorageSync('serverUrl');
	if (httpWhiteList.includes(config.url)) {
		// config.baseURL='https://hgcc.metaxun.com/MetaXunDataCenter'
		config.baseURL='http://192.168.110.17:8002/mixedStateZY/'
	}else {
		if (serverUrl) {
			config.baseURL = serverUrl ? serverUrl : BASE_API
		}
	}
	// config.baseURL='http://192.168.110.7:8004/MetaXunDataCenter'
	if (token) {
		config.header = {
			"Authorization": 'Bearer ' + token
		}
	}
	return config
}, error => {
	return Promise.resolve(error)
})
http.interceptors.response.use((response) => {
	console.log(response);
	uni.hideLoading()
	const code = response.data.code || 200;
	if (code === 200) {
		return response.data

	} else if (code === 401 || code === 404) {
		uni.showToast({
			title: '登录超时请重新登录',
			icon: 'none',
			duration: 1500
		});
		// return response.data
		uni.removeStorageSync("token")
		setTimeout(() => {
			var pages = getCurrentPages(); // 获取栈实例
			let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
			uni.redirectTo({
				url: `/pages/login/login?currentRoute=${currentRoute}`
			})
		}, 1500)

	} else {
		if (response.data.msg == '课程学习记录不存在') {
			return Promise.resolve('课程学习记录不存在')
		} else {
			uni.showToast({
				title: response.data.msg || '请求错误',
				icon: 'none',
				duration: 1500
			});
			return Promise.reject(response)
		}

	}
}, (error) => {
	console.log(error);
	uni.showToast({
		title: "网络错误",
		icon: 'none',
		duration: 1500
	});
	uni.hideLoading()
	return Promise.reject(error)

})
export {
	http,
	BASE_API
};